import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    list:[],
    inpValue:'手机',
    //下一个要添加数据的id值
    nextId:5,
    //选择的值 默认为0
    activeIndex:0
  },
  mutations: {
    initList(state,list){
      state.list = list
    },
    //改变inpvalue的值
    setInpVal(state,val){
      state.inpValue = val;
    },
    //添加事件
    addTaskForm(state){
      state.list.push({
        id:state.nextId,
        info:state.inpValue.trim(),
        done:false
      })
      state.nextId++
      state.inpValue = ''
    },
    //删除事件
    remove(state,id){
      //找到要删除的数据在list中的索引值
      const i = state.list.findIndex(item => item.id === id)
      //删除数据
      state.list.splice(i,1)
    },
    //修改事件状态
    editStatus(state,id){
      //根据id查找索引
      const i = state.list.findIndex(item => item.id === id)
      //根据索引 删除数据
      state.list[i].done = !state.list[i].done;
    },
    //清除已完成
    clearDone(state){
      state.list = state.list.filter(item => !item.done)
    },
    //修改选中的按钮
    setActiveIndex(state,index){
      state.activeIndex = index;
    }
  },
  actions: {
    async getList($store){
      const {data} = await axios.get('/list.json')
      $store.commit('initList',data)
    }
  },
  modules: {
  },
  getters:{
    unDoneTotal(state){
      return state.list.filter(item => !item.done).length;
    },
    filterList(state){
      if(state.activeIndex === 0) return state.list
      if(state.activeIndex === 1) return state.list.filter(item => !item.done)
      if(state.activeIndex === 2) return state.list.filter(item => item.done)
    }
  }
})
